<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
    </div>

    <el-table v-loading="listLoading" :key="tableKey" :data="list" element-loading-text="加载中" border fit highlight-current-row style="width: 100%">
      <el-table-column :label="$t('table.id')" align="center" width="65">
        <template slot-scope="scope">
          <span>{{ scope.$index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.idcName')" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.idcLevel')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.idclevelName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.cabinetCount')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.cabinetCount }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.phone')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.linkman')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.linkman }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.address')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.email')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.concatEmail }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.isp')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.ispNames }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.supplier')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.supplierName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.comment')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.comment }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.createTime')" width="180px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.creator')" width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.creator }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.updateTime')" width="180px">
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.updator')" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updator }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" fixed="right" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button v-if="scope.row.status!='deleted'" size="mini" type="danger" @click="handleDelete(scope.row)">{{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="110px" style="width: 400px; margin-left:50px;">
        <el-form-item :label="$t('table.idcName')" prop="name">
          <el-input v-model="temp.name"/>
        </el-form-item>
        <el-form-item :label="$t('table.phone')" prop="phone">
          <el-input v-model="temp.phone"/>
        </el-form-item>
        <el-form-item :label="$t('table.linkman')" prop="linkman">
          <el-input v-model="temp.linkman"/>
        </el-form-item>
        <el-form-item :label="$t('table.address')">
          <el-input v-model="temp.address"/>
        </el-form-item>
        <el-form-item :label="$t('table.email')" prop="concatEmail">
          <el-input v-model="temp.concatEmail"/>
        </el-form-item>
        <el-form-item :label="$t('table.signTime')" prop="signTime">
          <el-date-picker v-model="temp.signTime" type="datetime" placeholder="请选择签约时间"/>
        </el-form-item>
        <el-form-item :label="$t('table.signEndTime')" prop="endTime">
          <el-date-picker v-model="temp.endTime" type="datetime" placeholder="请选择合同到期时间"/>
        </el-form-item>
        <el-form-item :label="$t('table.idcLevel')" prop="typeId">
          <el-select v-model="temp.typeId" class="filter-item" placeholder="请选择机房等级">
            <el-option v-for="item in idcLevelOptions" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.supplier')" prop="supplierId">
          <el-select v-model="temp.supplierId" class="filter-item" placeholder="请选择供应商">
            <el-option v-for="item in supplierOptions" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.isp')">
          <el-select v-model="operatorIdArray" multiple placeholder="请选择ISP">
            <el-option
              v-for="item in ispOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.comment')">
          <el-input :autosize="{ minRows: 2, maxRows: 4}" v-model="temp.comment" type="textarea"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{ $t('table.confirm') }}</el-button>
        <el-button v-else type="primary" @click="updateData">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel"/>
        <el-table-column prop="pv" label="Pv"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList, fetchIdcLevel, fetchSupplier, fetchIsp, create, update, del } from '@/api/idc'
import { validPhone, validateEmail } from '@/utils/validate'

export default {
  name: 'ComplexTable',
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    const isPhone = (rule, value, callback) => {
      if (value) {
        if (validPhone(value)) {
          callback()
        } else {
          callback(null)
        }
      } else {
        callback()
      }
    }
    const isEmail = (rule, value, callback) => {
      if (value) {
        if (validateEmail(value)) {
          callback()
        } else {
          callback(null)
        }
      } else {
        callback()
      }
    }
    return {
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      idcLevelOptions: [],
      ispOptions: [],
      supplierOptions: [],
      operatorIdArray: [],
      showReviewer: false,
      temp: {
        id: undefined,
        name: '',
        linkman: '',
        comment: '',
        address: '',
        concatEmail: '',
        operatorIds: '',
        supplierId: undefined,
        typeId: undefined,
        signTime: '',
        endTime: '',
        phone: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        phone: [{ required: true, message: '请填写正确的联系电话', trigger: 'blur', validator: isPhone }],
        concatEmail: [{ message: '请填写正确的联系邮箱', trigger: 'blur', validator: isEmail }],
        linkman: [{ required: true, message: '联系人是必填项', trigger: 'blur' }],
        typeId: [{ required: true, message: '机房等级是必填项', trigger: 'blur' }],
        supplierId: [{ required: true, message: '供应商是必填项', trigger: 'blur' }],
        signTime: [{ required: true, message: '签约时间是必填项', trigger: 'blur' }],
        endTime: [{ required: true, message: '合同到期时间是必填项', trigger: 'blur' }],
        name: [{ required: true, message: '机房名称是必填项', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    this.getIdcLevelList()
    this.getSupplierList()
    this.getIspList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    getIdcLevelList() {
      fetchIdcLevel().then(response => {
        this.idcLevelOptions = response.data.records
      })
    },
    getIspList() {
      fetchIsp().then(response => {
        this.ispOptions = response.data.records
      })
    },
    getSupplierList() {
      fetchSupplier({ type: 'idc' }).then(response => {
        this.supplierOptions = response.data.records
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleDelete(row) {
      this.$confirm('此删除操作不可还原, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(row).then(response => {
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      }).catch(() => {
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        linkman: '',
        comment: '',
        address: '',
        concatEmail: '',
        operatorIds: '',
        supplierId: undefined,
        typeId: undefined,
        signTime: '',
        endTime: '',
        phone: ''
      }
    },
    handleCreate() {
      this.resetTemp()

      this.operatorIdArray = []
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (this.operatorIdArray.length === 0) {
          alert('ISP类型是必填项')
          return
        }
        if (valid) {
          if (this.operatorIdArray.length === 1) {
            this.temp.operatorIds = this.operatorIdArray[0]
          }
          if (this.operatorIdArray.length > 1) {
            this.temp.operatorIds = this.operatorIdArray.join(',')
          }
          const tempData = Object.assign({}, this.temp)
          create(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.operatorIdArray = []
      if (this.temp.operatorIds.indexOf(',') !== -1) {
        var operatorIdStrArray = this.temp.operatorIds.split(',')
        for (var i = 0; i < operatorIdStrArray.length; i++) {
          this.operatorIdArray.push(parseInt(operatorIdStrArray[i]))
        }
      } else {
        if (this.temp.operatorIds !== '') {
          this.operatorIdArray[0] = parseInt(this.temp.operatorIds)
        }
      }

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      if (this.operatorIdArray.length === 0) {
        alert('ISP类型是必填项')
        return
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.operatorIdArray.length === 0) {
            this.temp.operatorIds = ''
          }
          if (this.operatorIdArray.length === 1) {
            this.temp.operatorIds = this.operatorIdArray[0]
          }
          if (this.operatorIdArray.length > 1) {
            this.temp.operatorIds = this.operatorIdArray.join(',')
          }
          const tempData = Object.assign({}, this.temp)
          update(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    }
  }
}
</script>
